/* 目标：给选区内每个“剪切组”缩放到指定宽高（单位 mm），带 ScriptUI 对话框。 */
(function () {
    if (app.documents.length === 0) { alert("没有打开文档。"); return; }
    var doc = app.activeDocument;
    var sel = doc.selection;
    if (!sel || sel.length === 0) { alert("请先选中一个或多个剪切蒙版组。"); return; }

    // === 单位换算 ===
    var MM_TO_PT = 72 / 25.4;
    function mm2pt(mm) { return mm * MM_TO_PT; }
    function pt2mm(pt) { return pt / MM_TO_PT; }

    // === 工具函数：提升到最上层剪切组；查找剪切路径 ===
    function getTopClipGroup(item) {
        var p = item, lastClip = null;
        while (p) {
            if (p.typename === "GroupItem" && p.clipped) lastClip = p;
            if (!p.parent || p.parent.typename === "Document") break;
            p = p.parent;
        }
        return lastClip || item;
    }
    function findClippingPath(groupItem) {
        if (groupItem.typename !== "GroupItem") return null;
        for (var i = 0; i < groupItem.pageItems.length; i++) {
            var it = groupItem.pageItems[i];
            if (it.clipping === true) return it;
        }
        return null;
    }

    // === ScriptUI 对话框 ===
    var dlg = new Window("dialog", "统一缩放（mm）");
    dlg.orientation = "column";
    dlg.alignChildren = "fill";

    // 标题行
    var header = dlg.add("group");
    header.orientation = "row";
    header.add("statictext", undefined, "将所选剪切组缩放到指定尺寸（以剪切路径几何尺寸为基准）");

    // 输入区
    var gInputs = dlg.add("panel", undefined, "目标尺寸");
    gInputs.orientation = "column";
    gInputs.alignChildren = "fill";
    gInputs.margins = 12;

    var gRow1 = gInputs.add("group"); gRow1.orientation = "row";
    var lblW = gRow1.add("statictext", undefined, "宽 (mm)");
    lblW.preferredSize.width = 60;
    var edW  = gRow1.add("edittext", undefined, "100");
    edW.characters = 10;

    var gRow2 = gInputs.add("group"); gRow2.orientation = "row";
    var lblH = gRow2.add("statictext", undefined, "高 (mm)");
    lblH.preferredSize.width = 60;
    var edH  = gRow2.add("edittext", undefined, "100");
    edH.characters = 10;

    var gOpts = dlg.add("panel", undefined, "选项");
    gOpts.orientation = "column";
    gOpts.alignChildren = "left";
    gOpts.margins = 12;

    var cbLock = gOpts.add("checkbox", undefined, "保持比例（以宽为主，自动改高）");
    cbLock.value = false;

    var cbUseClip = gOpts.add("checkbox", undefined, "以剪切路径作为基准（推荐）");
    cbUseClip.value = true;

    var cbStroke = gOpts.add("checkbox", undefined, "描边随缩放（视觉更一致）");
    cbStroke.value = true;

    // 按钮
    var gBtns = dlg.add("group");
    gBtns.alignment = "right";
    var btnOK = gBtns.add("button", undefined, "确定", {name:"ok"});
    var btnCancel = gBtns.add("button", undefined, "取消", {name:"cancel"});

    // 输入校验 & 比例联动
    function parseNum(s) {
        if (s === null || s === undefined) return NaN;
        var v = parseFloat(String(s).replace(/,/g, "."));
        return (isNaN(v) ? NaN : v);
    }
    function updateHeightIfLocked() {
        if (!cbLock.value) return;
        var w = parseNum(edW.text);
        var h = parseNum(edH.text);
        if (isNaN(w) || w <= 0) return;
        // 用当前选区第一项（或剪切路径）比例，计算目标高
        var it0 = getTopClipGroup(sel[0]);
        var base = cbUseClip.value ? findClippingPath(it0) : it0;
        var bw = base ? base.width : it0.width;
        var bh = base ? base.height : it0.height;
        if (bw > 0 && bh > 0) {
            var ratio = bh / bw;
            edH.text = (w * ratio).toFixed(3);
        }
    }
    edW.onChanging = function(){ if (cbLock.value) updateHeightIfLocked(); };

    // 运行
    if (dlg.show() !== 1) return;

    var wmm = parseNum(edW.text), hmm = parseNum(edH.text);
    if (!(wmm > 0) || !(hmm > 0)) { alert("请输入有效的宽/高（mm）。"); return; }

    var targetW_pt = mm2pt(wmm);
    var targetH_pt = mm2pt(hmm);

    // === 缩放执行 ===
    var changed = 0, skipped = 0;

    // 逐项处理（尽量避免遍历深层对象，仅遍历选区）
    for (var i = 0; i < sel.length; i++) {
        var it = getTopClipGroup(sel[i]);
        try {
            if (it.locked || it.hidden) { skipped++; continue; }

            var base = (cbUseClip.value && it.typename === "GroupItem") ? findClippingPath(it) : null;
            var baseW = (base ? base.width : it.width);
            var baseH = (base ? base.height : it.height);

            if (!(baseW > 0) || !(baseH > 0)) { skipped++; continue; }

            // 计算百分比
            var sx = (targetW_pt / baseW) * 100;
            var sy = (targetH_pt / baseH) * 100;

            // 生成缩放矩阵并应用（中心缩放；描边是否随缩放由 cbStroke 控制）
            var m = app.getScaleMatrix(sx, sy);
            it.transform(
                m,
                true,   // changePositions
                true,   // changeFillPatterns
                true,   // changeFillGradients
                true,   // changeStrokePattern
                !!cbStroke.value, // changeLineWidths
                Transformation.CENTER
            );
            changed++;
        } catch (e) {
            skipped++;
        }
    }

    alert("完成：缩放 " + changed + " 项；跳过 " + skipped + " 项。");
})();
